package fi.laurea.datalogger;

import com.pretty_tools.dde.client.DDEClientConversation;
import com.pretty_tools.dde.client.DDEClientException;
import com.pretty_tools.dde.client.DDEMLException;

import fi.laurea.jsonbus.Sender;

public class Main {
	private static final String SERVICE = "PLW";
	private static final String TOPIC = "Current";

	public static void main(String[] args) {

		DataListener listener1 = new DataListener("data", "Eka");
		Sender sender = new Sender("dEMO");
		try {

			// prepare conversation
			final DDEClientConversation conversation = new DDEClientConversation();

			// connect with service and topic names
			conversation.connect(SERVICE, TOPIC);
			try {
				// loop forever making requests
				while (true) {

					// response to the request "Name" is a String where variable
					// names are separated by line breaks
					String response = "";
					response = conversation.request("Name");

					// response is now split to String array by line breaks
					String[] names = response.split(System
							.getProperty("line.separator"));

					// response to the request "Value" is a String where
					// variable values are separated by line breaks
					response = conversation.request("Value");
					String[] values = response.split(System
							.getProperty("line.separator"));

					// now the names and values tables are looped trough and
					// printed out
					for (int i = 0; i < names.length; i++) {
						System.out.println(names[i] + " " + values[i]);
					}

					// the DDE is updated around once a second
					// let the thread sleep for 1000 milliseconds before new
					// values are read
					Thread.sleep(1000);
					DataMessage message = new DataMessage();
					message.setNames(names);
					message.setValues(values);

					sender.sendGlobally(message);
				}

			} finally {
				conversation.disconnect();
			}
		} catch (DDEMLException e) {
			System.out.println("DDEMLException: 0x"
					+ Integer.toHexString(e.getErrorCode()) + " "
					+ e.getMessage());
		} catch (DDEClientException e) {
			System.out.println("DDEClientException: " + e.getMessage());
		} catch (Exception e) {
			System.out.println("Exception: " + e);
		}
	}
}